use crate::duck::read;
use crate::error::{AppError, Result};
use crate::routes::handler::RouteHandler;
use crate::routes::payload::Payload;
use crate::routes::response::Response;
use crate::schemas::duck::DuckData;
use crate::{extract_payload, services};
use async_trait::async_trait;

pub struct LoadDatasource;

#[async_trait]
impl RouteHandler for LoadDatasource {
    async fn handle(&self, _payload: Payload) -> Result<Response, AppError> {
        let form = extract_payload!(_payload, Payload::OperateDatasource)?;
        // 查询数据源对象
        let data = services::duck::load_file(form.id).await?;
        //
        Ok(Response::DuckData(data))
    }
}

pub struct TableAll;
#[async_trait]
impl RouteHandler for TableAll {
    async fn handle(&self, _payload: Payload) -> Result<Response, AppError> {
        let form = extract_payload!(_payload, Payload::OperateDatasource)?;

        // 先验证表是否存在
        let is_exit = read::table_exist(&form.id)?;

        let data: DuckData;

        if is_exit {
            // 存在就直接读取
            data = read::table_all(&form.id)?;
        } else {
            // 不存在就先加载
            data = services::duck::load_file(form.id).await?;
        }

        Ok(Response::DuckData(data))
    }
}
